<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/25
 * Time: 22:20
 */

namespace app\api\service;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    //生成一个32位的随机的字符串
    public static function generalToken()
    {
        //通过一个函数来拿到一个随机长度的字符串
        $randChars = getRandChars(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }
    //封装一个方法，便于获得token中的值
    public static function getCurrentTokenVar($key)
    {
        //获取header中的token
        $token = Request::instance() -> header('token');
        $vars = Cache::get($token);
        if(!$vars) throw new TokenException();
        if(!is_array($vars)) $vars = json_decode($vars, true);
        if(array_key_exists($key, $vars)) return $vars[$key];
        throw new Exception('获取的token变量不存在！');
    }
    //获取用户的uid
    public static function getCurrentUid()
    {
        return $uid = self::getCurrentTokenVar('uid');
    }
    //定义验证用户权限的方法
    public static function checkPrimaryScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if($scope) {
            if($scope < ScopeEnum::User) throw new ForbiddenException();
            return true;
        }else {
            throw new TokenException();
        }
    }
    //定义一个是否为管理员的方法
    public static function checkExclusiveScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if($scope) {
            if($scope >= ScopeEnum::Super) throw new ForbiddenException();
            return true;
        }else {
            throw new TokenException();
        }
    }
    //定义一个方法用在servicePay中,用于检查uid是否一致
    public static function checkValUid($checkUid)
    {
        if(!$checkUid) throw new Exception(['msg' => '必须传入一个uid']);
        $currentOperateUid = self::getCurrentUid();
        if($currentOperateUid == $checkUid) return true;
        return false;
    }
}